#!/bin/sh
# Generate a blog page with recent articles 
# 
# usage : swx_blog page.html
# if ":::BLOG:::" is found in page.html, it will be replaced by recent articles
# change it in swx.conf

# Load config file
if [ ! -f $PWD/swx.conf ]; then
	echo "Cannot find swx.conf in current directory"
	exit 1
fi

. $PWD/swx.conf

if [ ! -f "$LOG" ]; then
    echo "Can't find the News file"
    exit 1
fi

if [ -z "$1" ]; then
    "usage : $0 page.html"
    exit 1
fi

WORKTMP=$(mktemp)
# keep MAX news
uniq -u "$LOG" | tail -n $MAX > "$WORKTMP"
mv "$WORKTMP" "$LOG"

# new entry first
tac "$LOG" > $WORKTMP

NEWS=""
while read line; do
    NEWTITLE="$(basename $line | sed -e "s,$EXT$,,g")"
    if [ "$NEWTITLE" = "index" ]; then
        NEWTITLE="$(basename $(dirname $line))"
    fi
    URL="$(echo $line | cut -d'/' -f2- | sed -e "s,$EXT$,.html,g")"
    PUBDATE="$(stat -c %z "$line")"

    NEWS="\n$NEWS <div class='article'>\n"
    NEWS="$NEWS\n <a href="$URL">$NEWTITLE - $PUBDATE </a>"
    NEWS="$NEWS\n $($CONVERTER $line) "
    NEWS="$NEWS </div>"
done < $WORKTMP

echo "" > $WORKTMP

while read line; do
    if [ "$line" != "$NEWSSTR" ]; then
        echo "$line" >> $WORKTMP
    else
        echo "$NEWS" >> $WORKTMP
    fi
done < "$1"

mv $WORKTMP "$1"

exit 0
